import React from 'react';
import {message, Radio, Checkbox, Button, Select, Input, Form, Icon, Switch, Table, Upload, Alert} from 'antd';
import {
    API_URL,
    FetchURL,
    fetchArgs,
    SPECIALIST,
    formItemLayout,
    fetchPortrait,
    _validate,
    createSpecialist,
    updateSpecialist,
    check_rules,
    available,
    checkExists,
    fetchData,
    fetchDatum,
    portraitSet,
    fetchAttachByEntry,
  fetchAttachById
} from '../store/actions';
import _ from 'lodash';
const CheckboxGroup = Checkbox.Group,
    FormItem = Form.Item,
    Option = Select.Option,
    RadioGroup = Radio.Group,
    RadioButton = Radio.Button;

const tempServiceData = [
        {
            id: 'time0',
            label: '9:00-12:00'
        }, {
            id: 'time1',
            label: '14:00-17:00'
        }, {
            id: 'time2',
            label: '19:00-21:00'
        }
    ];
class FormEditSpecialist extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: {},
            status: this.props._target && this.props._target.status == 1 ? '已启用' : '已停用' || '已停用',
            statusCode: this.props._target && this.props._target.status || 0,
            specialist: this.props._target,
            portrait: {},
            fileList:{},
            user:this.props.user
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
        this.switchChange = this.switchChange.bind(this);
    }

    resetFields() {
        this.props.form.resetFields()
    }

    static contextTypes = {
        router: React.PropTypes.object
    };

    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        _validate(e, _this, function (data) {
            if (_this.state.statusCode == 1) {
                data.status = 1
            } else {
                data.status = 0
            }
            let _data = Object.assign({}, data);
            let workingtime = [];
            for (let _e in data) {
                const _reg = /^time\d+/;
                if (_reg.test(_e)) {
                    const _wt = {
                        label: _e,
                        weekday: data[_e]
                    };
                    workingtime.push(_wt);
                    delete _data[_e];
                }
            }
            _data.workingtime = workingtime;
            _data.ispass = 1;
            _data.specialstatus = 1;
            let attachment = [],
              willUploadFiles = _this.state.fileList;
            _.forIn(willUploadFiles,(v,k)=>{
                if(v.length> 0 ){
                    attachment.push({[k]:v})
                }
            })
            _data.attachment = attachment;
            if (_this.props.id) {
                _data.specialist_id = _this.props._target.specialist_id;
                _this.props.dispatch(updateSpecialist(_this.props.id, _data, function (res) {
                    message.success('专家（' + data.username + '）信息更新成功', 3);
                    _this.context.router.push('/specialist-list')
                }))
            } else {
                _this.props.dispatch(createSpecialist(_data, function (res) {
                    message.success('成功创建了专家账号' + data.username + '，初始密码是 123456', 3);
                    _this.context.router.push('/specialist-list')
                }))
            }
        })
    }
    componentWillMount() {
        const _this = this;
        _this.props.dispatch(fetchDatum([
            {
                name: 'department',
                enabled: true
            }, {
                name: 'title',
                enabled: true
            }, {
                name: 'gender',
                enabled: true
            }, {
                name: 'modality',
                enabled: true
            }
        ], function (datas) {
            _this.setState({
                data: datas
            })
        }));
        //rules
        _this.props.dispatch(check_rules(function (rules) {
            _this.setState({
                rules: rules.content
            })
        }));
        const {setFieldsValue} = _this.props.form;
        if (_this.props.id) {
            const initData = Object.assign({}, _this.props._target);
            if (initData.workingtime == '[]') {
            } else {
                //有数据
                const _wt = initData.workingtime;
                if(_wt) {
                    _wt.forEach(_w => {
                        initData[_w.label] = _w.weekday
                    });
                }
                delete initData.workingtime
            }
            _this.props.dispatch(fetchAttachByEntry({id:initData.specialist_id,type:'portrait'},function (portrait) {
                let last = {};
                if(portrait.content.length> 1){
                    _.forEach(portrait.content,(o,i)=>{
                        if((i+1)<portrait.content.length){
                            _this.props.dispatch(fetchAttachById(o.id,0));
                        }else{
                            last = o
                        }
                    })
                }else{
                    last = portrait.content[0]
                }
                _this.setState({
                    portrait: {
                        id:last.id,
                        url:`${API_URL}attachment/${last.id}?accessToken=${_this.state.user.accessToken}`
                    }
                })
            }));
            setFieldsValue(initData);
        } else {
            setFieldsValue();
            this.switchChange(true);
        }
    }

    componentWillReceiveProps(nextProp) {}

    checkForm(a, b, rule, value, callback) {
        const _r = eval(this.state.rules[a][b]['expr']),
            msg = this.state.rules[a][b]['rule'];
        (function () {
            const result = _r.test(value);
            if (!result && value) {
                callback(msg)
            } else {
                callback();
            }
        })()
    }
    checkUserName(rule, value, callback) {
        this.checkForm('account', 'username', rule, value, callback)
    }
    userExists(rule, value, callback) {
        const _this = this;
        if (_this.props._target) {
            this.props.dispatch(checkExists('username', rule, value, callback, _this.props._target.username))
        } else {
            this.props.dispatch(checkExists('username', rule, value, callback))
        }
    }

    checkName(rule, value, callback) {
        this.checkForm('account', 'name', rule, value, callback)
    }

    checkMob(rule, value, callback) {
        this.checkForm('common', 'mobile', rule, value, callback)
    }

    mobExists(rule, value, callback) {
        const _this = this;
        if (_this.props._target) {
            this.props.dispatch(checkExists('mobile', rule, value, callback, _this.props._target.mobile))
        } else {
            this.props.dispatch(checkExists('mobile', rule, value, callback))
        }
    }

    checkIdcard(rule, value, callback) {
        this.checkForm('common', 'idcard', rule, value, callback)
    }

    switchChange(e) {
        if (e) {
            this.setState({
                status: '已启用',
                statusCode: 1
            })
        } else {
            this.setState({
                status: '已停用',
                statusCode: 0
            })
        }
    }

    normFile(e) {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }

    portraitHandler(info){
        const _this = this;
        return portraitSet(info,_this)
    }
    fileTypeLimit(types,file){
        const fileType = file.type,
          typeStr = types.join('、');
        let isOk = false;
        for(let i = 0;i<types.length;i++){
            try{
                isOk = new RegExp(types[i]).test(fileType);
                if(isOk){
                    break;
                }
            }catch(e){consloe.log(e)}
        }
        if(!isOk){
            message.error(`您上传文件的格式只能是：${typeStr}格式`);
            return isOk
        }

    }

    render() {
        const _modalities = this.state.data.modality && _.map(this.state.data.modality, (_m) => {
                    return {
                        label: _m.code,
                        value: _m.id
                    }
                }),
            _departments = this.state.data.department && this.state.data.department.map(_h => {
                    return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
                }),
            _gender = this.state.data.gender && this.state.data.gender.map(_g => {
                    return (<RadioButton key={_g.id} value={_g.code}>{_g.name}</RadioButton>)
                }),

            _title = this.state.data.title && this.state.data.title.map(_h => {
                    return (<Option key={_h.id} value={_h.name}>{_h.name}</Option>)
                }),
            {getFieldProps, getFieldError, isFieldValidating} = this.props.form;
        if (this.state.roleFetch) {
            return (<div>loading...</div>)
        } else {
            const specialistUsername = getFieldProps('username', {
                rules: [
                    {required: true, message: '请输入用户名'},
                    {validator: this.checkUserName.bind(this)},
                    {validator: this.userExists.bind(this)}
                ],
                validateTrigger: 'onBlur'
            });
            const specialistName = getFieldProps('name', {
                rules: [
                    {required: true, message: '请输入医生姓名'},
                    {validator: this.checkName.bind(this)}
                ]
            });
            const specialistHospital = getFieldProps('hospital', {
                rules: [
                    {required: true, message: '请选择所属医院'},
                    {max: 100, message: '所属医院最大长度为100'}
                ]
            });
            const specialistDepartment = getFieldProps('department', {
                rules: [
                    {required: true, message: '请选择所属科室'}
                ]
            });
            const specialistTitle = getFieldProps('title', {
                rules: [
                    {required: true, message: '请选择职称'}
                ]
            });
            const specialistDesc = getFieldProps('brief_introduction', {
                rules: [
                    {required: true, message: '请输入医生介绍'},
                    {max: 5000, message: '超过了最大长度5000'}
                ]
            });
            const specialistDomain = getFieldProps('domain', {
                rules: [
                    {required: true, message: '请输入医生擅长领域'},
                    {max: 5000, message: '超过了最大长度5000'}
                ]
            });
            const specialistModalities = getFieldProps('modalities', {
                rules: [
                    {required: true, type: 'array', message: '请勾选医生阅片类型'}
                ]
            });
            const specialistStatus = getFieldProps('status');

            const mobProps = getFieldProps('mobile', {
                rules: [
                    {required: true, message: '请输入手机号'},
                    {validator: this.checkMob.bind(this)},
                    {validator: this.mobExists.bind(this)}
                ],
                validateTrigger: 'onBlur'
            });
            const idCardProps = getFieldProps('idcard', {
                rules: [
                    {required: false},
                    {validator: this.checkIdcard.bind(this)}
                ]
            });
            const genderProps = getFieldProps('gender', {
                rules: [
                    {required: true, message: '请选择专家性别'}
                ]
            });
            const dateData = [
                {label: '周一', value: 1},
                {label: '周二', value: 2},
                {label: '周三', value: 3},
                {label: '周四', value: 4},
                {label: '周五', value: 5},
                {label: '周六', value: 6},
                {label: '周日', value: 7}
            ];
            const serviceColumns = [
                {
                    title: '时间段',
                    dataIndex: 'label',
                    width: 90,
                    size: 'small'
                }, {
                    title: '日期',
                    dataIndex: 'active',
                    render(text, record){
                        const _d = getFieldProps(record.id, {
                            rules: [
                                {type: 'array'}
                            ]
                        });

                        return (
                            <CheckboxGroup
                                {..._d}
                                options={dateData}
                            />
                        )
                    }
                }
            ];
            const portraitProps = getFieldProps('portrait', {
                normalize: this.normFile.bind(this),
                onChange: this.portraitHandler.bind(this)
            });
            let curPortrait = null;
            if(this.state.fileList && this.state.fileList.portrait){
                curPortrait = {};
                const _id = this.state.fileList.portrait;
                curPortrait.id = _id;
                curPortrait.url = `${API_URL}attachment/${_id}?accessToken=${this.state.user.accessToken}`
            }else{
                curPortrait = this.state.portrait
            }
            return (
                <Form horizontal form={this.props.form}>
                    {this.state.specialist ?
                        '' : <Alert message='新建专家账号成功后，可以在编辑界面上传头像' closeText="知道了"/>
                    }
                    <FormItem
                        {...formItemLayout}
                        label="用户名"
                        hasFeedback
                        help={isFieldValidating('username') ? '校验中...' : (getFieldError('username') || []).join(', ')}
                    >
                        <p></p>
                        <Input
                            disabled={!!this.props.id}
                            {...specialistUsername}
                            placeholder="请输入用户名"
                        />
                    </FormItem>
                    {this.state.specialist ?
                      (<FormItem
                        {...formItemLayout}
                        label="专家头像"
                      >
                          <Upload
                            name="files"
                            showUploadList={false}
                            action={`${API_URL}upload/portrait?accessToken=${this.props.user.accessToken}`}
                            beforeUpload = {this.fileTypeLimit.bind(this,['jpg','gif','png','jpeg'])}
                            help="只能上传图片格式的文件"
                            {...portraitProps}
                          >
                              <div style={{
                                width: '100px',
                                overflow: 'hidden',
                                backgroundColor: '#ddd',
                                textAlign: 'center'
                            }}>
                                  {curPortrait?<img style={{
                            display: 'block',
                            width: '100%'
                        }} src={curPortrait.url} />:'没有上传头像'}
                              </div>
                              <Button type="ghost">
                                  <Icon type="upload" /> 选择并上传头像
                              </Button>
                          </Upload>
                      </FormItem>):''}
                    <FormItem
                        {...formItemLayout}
                        label="姓名"
                    >
                        <Input
                            {...specialistName}
                            placeholder="请输入专家姓名"
                        />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="性别"
                    >
                        <RadioGroup {...genderProps}>
                            {_gender}
                        </RadioGroup>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="职称"
                    >
                        <Select
                            {...specialistTitle}
                            showSearch
                            placeholder="请选择职称"
                            optionFilterProp="children"
                            notFoundContent="无法找到"
                        >
                            {_title}
                        </Select>
                    </FormItem>

                    <FormItem
                        {...formItemLayout}
                        label="身份证号"
                    >
                        <Input {...idCardProps} placeholder="请输入身份证号"/>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="所属医院"
                    >
                        <Input {...specialistHospital} placeholder="请输入所属医院"/>
                    </FormItem>
                    <FormItem {...formItemLayout} label="所属科室">
                        <Select {...specialistDepartment} showSearch placeholder="请选择所属科室" optionFilterProp="children"
                                notFoundContent="无法找到">{_departments}</Select>
                    </FormItem>
                    <FormItem {...formItemLayout.ignore} label="阅片类型">
                        <CheckboxGroup {...specialistModalities} options={_modalities}/>
                    </FormItem>
                    <FormItem {...formItemLayout} label="擅长领域">
                        <Input type="textarea" {...specialistDomain} />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="简介"
                    >
                        <Input type="textarea" {...specialistDesc} />
                    </FormItem>
                    <FormItem
                        label="手机号"
                        {...formItemLayout}
                        hasFeedback
                        help={isFieldValidating('mobile') ? '校验中...' : (getFieldError('mobile') || []).join(', ')}
                    >
                        <Input {...mobProps} placeholder="请输入手机号"/>
                    </FormItem>
                    <FormItem
                        label="服务时段"
                        {...formItemLayout.ignore}
                    >
                        <Table columns={serviceColumns} dataSource={tempServiceData} pagination={false}/>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="状态"
                    >
                        <Switch
                            {...specialistStatus}
                            onChange={this.switchChange}
                            defaultChecked={this.props._target ? (this.props._target.status == 1 ? true : false ): true}
                            value={this.state.status}
                        />
                        <span>&nbsp;&nbsp;{this.state.status || true}</span>
                    </FormItem>
                    {(this.state.showBtn != false) ? (<FormItem wrapperCol={formItemLayout.noLabel}>
                        <Button type="primary" onClick={this.handleSubmit}>保存</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="light" onClick={function () {
                            this.context.router.goBack(-1)
                        }.bind(this)}>取消</Button>
                    </FormItem>) : ''}
                </Form>

            )
        }
    }
}

export default FormEditSpecialist = Form.create()(FormEditSpecialist);